<?php
require 'Common.class.php';
require 'Agent.class.php';

$agent_obj    = new PWC\Agent($argv[1]); 
$args         = new stdClass;
$url          = $argv[3];

$args->url    = $url;
$args->agent  = $agent_obj;
$args->ticket = $argv[4];
$args->connect= $argv[2];
$status       = 200;

$contents = file_get_contents('php://stdin');

# get http headers
if(preg_match("/(?:\r\n){2}|\n{2}|\r{2}/",$contents,$position,PREG_OFFSET_CAPTURE)){
    $headers  = substr($contents,0,$position[0][1]);
    $contents = substr($contents,$position[0][1]+2);
    $args->headers = $headers;
}else{
    retry($agent_obj,$argv[2],$url,$args->ticket);
    exit("Error: [$url] [{$argv[2]}]\n$contents");
}

# get http response code
if(preg_match('/HTTP.+ (\d{3}) /', $headers, $matched)){
    $status = $matched[1];
}else{
    # Retrieve,retry
    retry($agent_obj,$argv[2],$url,$args->ticket);
    exit("Error: [$url] [{$argv[2]}]\n$contents");
}

# get cookies
if($has_cookie = strrpos($contents,'# Netscape HTTP Cookie File')){
    $agent_obj->setCookie($url,substr($contents,$has_cookie));
    $contents = substr($contents,0,$has_cookie);
}
$args->contents = $contents;

# call contents handler
try{
    foreach($agent_obj->getConfig()->processors as $processor){
        if(preg_match('#'.$processor['handle_status'].'#',$status)){
            require_once($processor['file']);
            call_user_func($processor['func'],$args);
        }
    }
    $agent_obj->processed($argv[2],$url);
}catch(exception $e){
    # Retrieve,retry
    retry($agent_obj,$argv[2],$url,$args->ticket);
}

function retry($agent,$connect,$url,$ticket){
    $agent->processed($connect,$url);
    sleep(1);
    $agent->addUrls(array($url),$ticket,null,true);
}
